package HibernateOrederManagement.app;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import HibernateOrderManagerment.bean.Store;
import HibernateOrderManagerment.bean.User;

public class StoreDao {
private Session session;
	
	public StoreDao(Session session){
		this.session=session;
	}
	
	public List<Store> list(){
		Query<Store> query=session.createQuery("from Store",Store.class);
		
		return query.getResultList();
	}
	
	public Store getStoreById(long id){
		return session.get(Store.class,id);
	}
	
	public Store getByName(String name){
		Query<Store> query =session.createQuery("from Store where name=:name",Store.class);
		query.setParameter("name", name);
		return query.getSingleResult();
	}
	public Store getByUserId(long id){
		UserDao dao =new UserDao(session);
		User user =dao.getUserById(id);
		Query<Store> query =session.createQuery("from Store where user=:user",Store.class);
		query.setParameter("user", user);
		return query.getSingleResult();
	}
	
	public void insert(Store store) {
		Transaction tx = session.beginTransaction();
		try {

			session.save(store);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
	}
	public void update(Store store){
		Transaction tx = session.beginTransaction();
		try {

			session.update(store);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
		
	}
	public void delete(Store store){
		Transaction tx = session.beginTransaction();
		try {
			
			session.delete(store);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
		
	}


}
